package com.brillilab.service.core.account.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.brillilab.common.entity.PageVo;
import com.brillilab.dao.mapper.account.UserAccountMapper;
import com.brillilab.domain.po.account.UserAccount;
import com.brillilab.domain.vo.account.AccountDetailedVo;
import com.brillilab.service.core.account.UserAccountService;
import com.github.pagehelper.PageHelper;

/**
* 用户账户表
* @author LJ
*/
@Service
@Transactional
public class UserAccountServiceImpl implements UserAccountService {

	@Resource
	private UserAccountMapper userAccountMapper;


	@Override
	public UserAccount getByUserId(Long userId) {
		LambdaQueryWrapper<UserAccount> wrapper = new LambdaQueryWrapper<UserAccount>();
				wrapper.eq(UserAccount::getUserId,userId);
		UserAccount userAccount = userAccountMapper.selectOne(wrapper);
		if(userAccount==null) {
			userAccount = new UserAccount();
			userAccount.setUserId(userId);
			userAccount.setTotalIntegral(0);
			userAccountMapper.insert(userAccount);
		}
		return userAccount;
	}

	@Override
	public int exchangeIntegral(Long userId) {
		UserAccount userAccount = this.getByUserId(userId);
		int totalIntegral = userAccount.getTotalIntegral();
		if(totalIntegral>0) {
			userAccount.setTotalIntegral(0);
			int i = userAccountMapper.updateById(userAccount);
			Assert.isTrue(i==1, "账户积分更新失败");
		}
		return totalIntegral;
	}
	
	@Override
	public UserAccount addIntegral(Long userId, int integral) {
		UserAccount userAccount = this.getByUserId(userId);
		int totalIntegral = userAccount.getTotalIntegral();
		
		userAccount.setTotalIntegral(totalIntegral+integral);
		int i = userAccountMapper.updateById(userAccount);
		Assert.isTrue(i==1, "账户积分更新失败");
		return userAccount;
	}

	@Override
	public PageVo<AccountDetailedVo> getAccountDetailed(Long userId,int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<AccountDetailedVo> list = userAccountMapper.getAccountDetailed(userId);
		return new PageVo<AccountDetailedVo>(list);
	}

}